package com.ajz.manager.api;


import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ajz.common.constants.SwaggerApiConstant;
import com.ajz.common.dto.Result;
import com.ajz.common.utils.RandomCodeUtil;
import com.ajz.manager.entity.Member;
import com.ajz.manager.entity.SysAppVersion;
import com.ajz.manager.service.MemberService;
import com.ajz.manager.service.SysAppVersionService;
import com.ajz.sendsms.service.AliyunService;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping(value = "/App")
public class AppLoginController {
//	@Autowired
//    private IUserService personService;
//	@Autowired
//	private BCryptPasswordEncoder bpe;
	@Inject
	private AliyunService aliyunService;
	@Inject
	private SysAppVersionService appVersionService;
	@Inject
	private MemberService memberService;
	/**
	 *	获取App最新版本
	 *
	 * @return
	 */
	@ApiOperation(value = SwaggerApiConstant.API_EXPLAIN_GET_NEW_APPVERSION)
	@RequestMapping(value = "/getAppversion", method = RequestMethod.POST)
	public Result getAppversion(
			@ApiParam(value = SwaggerApiConstant.API_PARAM_DEVICE_TYPE, required = true) @RequestParam(required = true) Integer deviceType) {
		SysAppVersion version = appVersionService.findByDeviceType(deviceType);
		return Result.successResult(version);
	}
	/**
     * 用户登录
     *
     * @param username 用户名
     * @param password 密码
     * @return 操作结果
     * @throws AuthenticationException 错误信息
     */
	@ApiOperation(value = SwaggerApiConstant.MEMBER_LOGIN)
    @PostMapping(value = "/login", params = {"username", "password"})
    public Result getToken(String username, String password) throws AuthenticationException {
    	String token = memberService.login(username, password);
        return Result.successResult(token);
    }

    /**
     * 用户注册
     *
     * @param user          用户信息
     * @return 操作结果
     * @throws AuthenticationException 错误信息
     */
	@ApiOperation(value = SwaggerApiConstant.MEMBER_REGISTER)
    @PostMapping(value = "/register")
    public Result register(@RequestBody Member user) throws AuthenticationException {
    	String res = memberService.register(user);
    	if (res.equals("success")) {
    		 return Result.successResult(memberService.register(user));
		}else {
			 return Result.errorResult(res);
		}
    }
    /**
     * 获取注册验证码
     * @param phone
     * @throws ServletException
     */
	@ApiOperation(value = SwaggerApiConstant.VERIFICATION_CODE_GET)
	@GetMapping("/getVerificationCode")
	public Result getCode(HttpServletRequest request,@RequestParam(value = "phone",required = false) String phone) {
		String code = RandomCodeUtil.randomCode(6);
		HttpSession session = request.getSession();
		//将code保存至session
		session.setAttribute(phone, code);
		session.setMaxInactiveInterval(60);
		try {
			aliyunService.sendVerificationCode(phone, code);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return Result.successResult();
	}
	/**
     * 验证注册码
     * @param phone
     * @throws ServletException
     */
	@ApiOperation(value = SwaggerApiConstant.VERIFICATION_CODE_CHECK)
	@GetMapping("/checkVerificationCode")
	public Result checkVerificationCode(HttpServletRequest request,@RequestParam(value = "phone",required = false) String phone,@RequestParam(value = "code",required = false) String code) {
		String vcode = (String)request.getSession().getAttribute(phone);
		if(vcode == null) {
			return Result.errorResult("验证码失效！");
		}
		if(vcode.equals(code)) {
			return Result.successResult();
		}
		return Result.errorResult("验证码错误！");
	}
//    /**
//     * User register with whose username and password
//     * @param reqPerson
//     * @return Success message
//     * @throws ServletException
//     */
//    @RequestMapping(value = "/register", method = RequestMethod.POST)
//    public String register(User reqPerson) throws ServletException {
//        // Check if username and password is null
//        if (reqPerson.getLoginName() == "" || reqPerson.getLoginName() == null
//                || reqPerson.getPassword() == "" || reqPerson.getPassword() == null)
//            throw new ServletException("Username or Password invalid!");
//
//        // Check if the username is used
//        if(personService.findByLoginName(reqPerson.getLoginName()) != null)
//            throw new ServletException("Username is used!");
//        
////        // Give a default role : MEMBER
////        List<Role> roles = new ArrayList<Role>();
////        roles.add(Role.MEMBER);
//
//        // Create a person in ignite
//        personService.save(reqPerson);
//        return "Register Success!";
//    }
//
//    /**
//     * Check user`s login info, then create a jwt token returned to front end
//     * @param reqPerson
//     * @return jwt token
//     * @throws ServletException
//     */
//    @PostMapping
//    public String login(User reqPerson) throws ServletException {
//        // Check if username and password is null
//        if (reqPerson.getLoginName() == "" || reqPerson.getLoginName() == null
//                || reqPerson.getPassword() == "" || reqPerson.getPassword() == null)
//            throw new ServletException("Please fill in username and password");
//
//        // Check if the username is used
//        User user = personService.findByLoginName(reqPerson.getLoginName());
//        if(user == null || bpe.matches(reqPerson.getPassword(), user.getPassword()) == false){
//            throw new ServletException("Please fill in username and password");
//        }
////        if(personService.findByLoginName(reqPerson.getLoginName()) == null
////                || !reqPerson.getPassword().equals(personService.findByLoginName(reqPerson.getLoginName()).getPassword())){
////            throw new ServletException("Please fill in username and password");
////        }
//
//        // Create Twt token
////        String jwtToken = Jwts.builder().setSubject(reqPerson.getLoginName()).claim("roles", "member").setIssuedAt(new Date())
////                .signWith(SignatureAlgorithm.HS256, "secretkey").compact();
//        String jwtToken = Jwts.builder().setSubject(reqPerson.getLoginName()).setIssuedAt(new Date())
//              .signWith(SignatureAlgorithm.HS256, "secretkey").compact();
//        return jwtToken;
//    }
}
